<template>
    <div class="user-div">
        <!-- 搜索工具栏 -->
        <el-row>
            <el-col :span="2">用户名：</el-col>
            <el-col :span="3">
                <el-input v-model="formParams.userName" placeholder="查询用户名" clearable/>
            </el-col>
            <el-col :span="2">邮箱：</el-col>
            <el-col :span="3">
                <el-input v-model="formParams.email" placeholder="查询邮箱" clearable/>
            </el-col>
            <el-col :span="13">
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button type="success" @click="handleInsert">新增</el-button>
                <el-button type="danger">批量删除</el-button>
            </el-col>
        </el-row>

        <!--  显示数据的表格 -->
        <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" align="center"/>
            <el-table-column prop="userId" label="用户ID" width="80"/>
            <el-table-column prop="userName" label="用户名" width="100"/>
            <el-table-column prop="email" label="邮箱" width="100"/>
            <el-table-column prop="isLocked" label="是否锁定" width="100"/>
            <el-table-column prop="roleName" label="角色">

            </el-table-column>


            <el-table-column align="right">
                <template #default="scope">
                    <el-button size="small" type="warning" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="page-div">
            <el-pagination layout="prev, pager, next"
                           :total="pageBean.total"
                           v-model:current-page="pageBean.currentPage"
                           v-model:page-size="pageBean.pageSize"
                           :page-sizes="[1, 2, 3, 4]"
                           @change="changePage"></el-pagination>
        </div>
    </div>

    <!-- 弹出框 -->
    <el-dialog :title="title" v-model="dialogFormVisible">
        <el-form :model="userForm" :rules="rules" ref="userFormBean">
            <el-form-item label="用户名" :label-width="formLabelWidth" prop="userName">
                <el-input v-model="userForm.userName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" :label-width="formLabelWidth" prop="password">
                <el-input v-model="userForm.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" :label-width="formLabelWidth" prop="checkPass">
                <el-input v-model="userForm.checkPass" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="email" :label-width="formLabelWidth">
                <el-input v-model="userForm.email" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="角色" :label-width="formLabelWidth">
                <el-select v-model="userForm.roleId" placeholder="请选择角色">
                    <el-option label="超级管理员" value="1"></el-option>
                    <el-option label="管理员" value="2"></el-option>
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleSubmit(userFormBean)">确 定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>

    import {onMounted, ref, reactive, watch} from "vue";
    import axios from '@/api/index.js'
    import {ElMessage} from "element-plus";
    import {clearObject} from "../../common/util";

    const tableData = ref([]);

    onMounted(() => {
        handleSearch()
        // getTotal()
    })

    //分页控制
    const pageBean = reactive({
        pageSize: 5,
        currentPage: 1,
        total: 0
    })

    const changePage = (currentPage, pageSize) => {
        pageBean.currentPage = currentPage
        pageBean.pageSize = pageSize
        handleSearch()
    }


    //查询操作
    let formParams = reactive({
        userName: '',
        email: ''
    })

    const handleSearch = () => {
        axios.post("/user/list", {...pageBean, ...formParams}).then(response => {
            tableData.value = response.data.data.list
            pageBean.total = response.data.data.total
        })
    }

    //删除操作
    const handleDelete = (row) => {
        axios.post("/user/delete",{userId:row.userId})
            .then(response => {
                handleSearch()
            })
    }


    /**------------ 添加操作 ------------*/
    const dialogFormVisible = ref(false)
    const formLabelWidth = '140px'
    const title = ref('添加用户')
    let userForm = reactive({
        id: 0,
        userName: 'abcdef',
        password: '111111',
        checkPass: '111111',
        email: '11@11.11',
        roleId: ''
    })

    const handleInsert = () => {
        title.value = '添加用户'
        dialogFormVisible.value = true
        // clearObject(userForm)
    }

    //表单验证
    //封装表单验证规则，可以自定义...
    const validatePass = (rule, value, callback) => {
        if (value === '') {
            callback(new Error('确认密码不能为空！'))
        } else if (value !== userForm.password) {
            callback(new Error("两次密码输入不一致!"))
        } else {
            callback()
        }
    }

    const rules = reactive({
        userName: [
            {required: true, message: '用户名不能为空！', trigger: 'blur'},
            {pattern: /^\w{5,10}$/, message: '格式不正确！', trigger: 'blur'},
        ],
        password: [
            {required: true, message: '密码不能为空！', trigger: 'blur'}
        ],
        checkPass: [{validator: validatePass, trigger: 'blur'}],
    })


    /**------------ 编辑操作 ------------*/
    const handleEdit = (row) => {
        userForm = row;
        title.value = "编辑用户"
        dialogFormVisible.value = true
    }


    /**------------ 提交表单 ------------*/
    const userFormBean = ref();
    const handleSubmit = (userForms) => {
        userForms.validate((valid, fields) => {
            if (valid) {
                let option = {
                    method: 'post',
                    url: '/user/insert',
                    data: userForm
                }
                if (title.value === '编辑用户') {
                    option.url = '/user/update' + userForm.id
                    option.method = "put"
                }
                axios(option)
                    .then(response => {
                        dialogFormVisible.value = false
                        handleSearch()
                    })
                    .catch(error => {
                        console.log(error)
                    });
            }
        })
    }

    //复选框操作
    const handleSelectionChange = (val) => {
        console.log(val)
    }
</script>
<style scoped>
    .user-div {
        background-color: #ffffff;
        height: 100%;
    }

    .el-row {
        height: 60px;
        line-height: 60px;
    }

    .el-pagination {
        margin: 10px auto;
    }

    .page-div {
        display: flex;
    }
</style>
